package com.gitee.alpha.ie.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import java.util.Map;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

/**
 * 单元格下拉选择框<br>
 *
 * @author 冰羽
 * @version 2.2.0
 */
public class SpinnerWriteHandler implements SheetWriteHandler {
  private Map<Integer, String[]> dropDownValues;
  private int firstRow = 1;
  private int lastRow = 1000;

  public SpinnerWriteHandler(Map<Integer, String[]> dropDownValues) {
    this.dropDownValues = dropDownValues;
  }

  public SpinnerWriteHandler(Map<Integer, String[]> dropDownValues, int firstRow) {
    this(dropDownValues);
    this.firstRow = firstRow;
  }

  public SpinnerWriteHandler(Map<Integer, String[]> dropDownValues, int firstRow, int lastRow) {
    this(dropDownValues, firstRow);
    this.lastRow = lastRow;
  }

  @Override
  public void beforeSheetCreate(
      WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}

  @Override
  public void afterSheetCreate(
      WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    Sheet sheet = writeSheetHolder.getSheet();

    // 设置下拉框
    DataValidationHelper helper = sheet.getDataValidationHelper();

    for (Map.Entry<Integer, String[]> entry : dropDownValues.entrySet()) {
      /** 起始行、终止行、起始列、终止列 */
      CellRangeAddressList addressList =
          new CellRangeAddressList(firstRow, lastRow, entry.getKey(), entry.getKey());
      /** 设置下拉框数据 */
      DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
      DataValidation dataValidation = helper.createValidation(constraint, addressList);
      /** 处理Excel兼容性问题 */
      if (dataValidation instanceof XSSFDataValidation) {
        dataValidation.setSuppressDropDownArrow(true);
        dataValidation.setShowErrorBox(true);
      } else {
        dataValidation.setSuppressDropDownArrow(false);
      }
      sheet.addValidationData(dataValidation);
    }
  }
}
